//package com.apimanage.gateway.filter;
//
//import com.apimanage.common.dto.ApiLogDTO;
//import com.apimanage.common.service.MonitorService;
//import org.apache.dubbo.config.annotation.DubboReference;
//import org.reactivestreams.Publisher;
//import org.springframework.cloud.gateway.filter.GatewayFilterChain;
//import org.springframework.cloud.gateway.filter.GlobalFilter;
//import org.springframework.cloud.gateway.filter.NettyWriteResponseFilter;
//import org.springframework.core.Ordered;
//import org.springframework.core.io.buffer.DataBuffer;
//import org.springframework.core.io.buffer.DataBufferFactory;
//import org.springframework.http.server.reactive.ServerHttpRequest;
//import org.springframework.http.server.reactive.ServerHttpResponse;
//import org.springframework.http.server.reactive.ServerHttpResponseDecorator;
//import org.springframework.stereotype.Component;
//import org.springframework.web.server.ServerWebExchange;
//import reactor.core.publisher.Mono;
//import java.nio.charset.StandardCharsets;
//import java.util.Date;
//
///**
// * 网关监控过滤器
// * 用于记录API调用日志和统计信息
// */
//@Component
//public class MonitorFilter implements GlobalFilter, Ordered {
//
//    @DubboReference(check = false)
//    private MonitorService monitorService;
//
//    @Override
//    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
//        // 记录请求开始时间
//        long startTime = System.currentTimeMillis();
//
//        // 创建日志对象
//        ApiLogDTO apiLog = new ApiLogDTO();
//        apiLog.setRequestTime(new Date(startTime));
//        apiLog.setRequestUri(exchange.getRequest().getURI().toString());
//        apiLog.setRequestMethod(exchange.getRequest().getMethod().name());
//        apiLog.setClientIp(getClientIp(exchange.getRequest()));
//
//        // 获取用户信息
//        String userId = exchange.getRequest().getHeaders().getFirst("userId");
//        if (userId != null) {
//            try {
//                apiLog.setUserId(Long.parseLong(userId));
//            } catch (NumberFormatException e) {
//                // 用户ID格式错误，忽略
//            }
//        }
//
//        // 获取API ID（如果在请求头中）
//        String apiIdHeader = exchange.getRequest().getHeaders().getFirst("apiId");
//        if (apiIdHeader != null) {
//            try {
//                apiLog.setApiId(Long.parseLong(apiIdHeader));
//            } catch (NumberFormatException e) {
//                // API ID格式错误，忽略
//            }
//        }
//
//        // 装饰响应，记录响应内容和状态
//        ServerHttpResponse originalResponse = exchange.getResponse();
//        DataBufferFactory bufferFactory = originalResponse.bufferFactory();
//
//        ServerHttpResponseDecorator decoratedResponse = new ServerHttpResponseDecorator(originalResponse) {
//            @Override
//            public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
//                if (body instanceof Mono) {
//                    Mono<? extends DataBuffer> monoBody = (Mono<? extends DataBuffer>) body;
//                    return super.writeWith(monoBody.map(dataBuffer -> {
//                        // 记录响应时间和耗时
//                        long endTime = System.currentTimeMillis();
//                        long costTime = endTime - startTime;
//                        apiLog.setResponseTime(new Date(endTime));
//                        apiLog.setCostTime(costTime);
//
//                        // 记录响应状态
//                        apiLog.setResponseStatus(this.getStatusCode().value());
//
//                        // 记录响应内容（实际项目中可能需要限制大小）
//                        byte[] content = new byte[dataBuffer.readableByteCount()];
//                        dataBuffer.read(content);
//                        String responseBody = new String(content, StandardCharsets.UTF_8);
//                        apiLog.setResponseBody(responseBody);
//
//                        // 异步记录日志
//                        saveApiLog(apiLog);
//
//                        // 重置数据缓冲区，以便后续处理
//                        return bufferFactory.wrap(content);
//                    }));
//                }
//                return super.writeWith(body);
//            }
//        };
//
//        // 继续过滤链
//        return chain.filter(exchange.mutate().response(decoratedResponse).build());
//    }
//
//    /**
//     * 获取客户端IP
//     */
//    private String getClientIp(ServerHttpRequest request) {
//        String clientIp = request.getHeaders().getFirst("X-Forwarded-For");
//        if (clientIp == null || clientIp.isEmpty() || "unknown".equalsIgnoreCase(clientIp)) {
//            clientIp = request.getHeaders().getFirst("Proxy-Client-IP");
//        }
//        if (clientIp == null || clientIp.isEmpty() || "unknown".equalsIgnoreCase(clientIp)) {
//            clientIp = request.getHeaders().getFirst("WL-Proxy-Client-IP");
//        }
//        if (clientIp == null || clientIp.isEmpty() || "unknown".equalsIgnoreCase(clientIp)) {
//            clientIp = request.getRemoteAddress() != null ? request.getRemoteAddress().getAddress().getHostAddress() : "unknown";
//        }
//        // 如果通过了多级代理，X-Forwarded-For的值可能有多个，第一个非unknown的有效IP即为真实IP
//        if (clientIp != null && clientIp.contains(",")) {
//            String[] ips = clientIp.split(",");
//            for (String ip : ips) {
//                if (!"unknown".equalsIgnoreCase(ip.trim())) {
//                    clientIp = ip.trim();
//                    break;
//                }
//            }
//        }
//        return clientIp;
//    }
//
//    /**
//     * 保存API调用日志
//     */
//    private void saveApiLog(ApiLogDTO apiLog) {
//        // 异步保存日志，避免阻塞主线程
//        new Thread(() -> {
//            try {
//                // 直接调用监控服务保存日志DTO
//                monitorService.recordApiLog(apiLog);
//
//                // 更新API调用统计
//                if (apiLog.getApiId() != null) {
//                    int status = apiLog.getResponseStatus() != null && apiLog.getResponseStatus() >= 200 && apiLog.getResponseStatus() < 400 ? 1 : 0;
//                    monitorService.updateApiStatistics(apiLog.getApiId(), status, apiLog.getCostTime());
//                }
//            } catch (Exception e) {
//                // 记录日志失败，不影响主流程
//                System.err.println("保存API调用日志失败：" + e.getMessage());
//            }
//        }).start();
//    }
//
//    @Override
//    public int getOrder() {
//        // 过滤器执行顺序，在NettyWriteResponseFilter之后
//        return NettyWriteResponseFilter.WRITE_RESPONSE_FILTER_ORDER - 1;
//    }
//
//}